dojo.provide("xray.tools.Timer");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("xray.tools.Timer", [dijit._Widget, dijit._Templated], {
	templateString: '<div dojoAttachPoint="log"></div>',
	
	constructor: function(){
		this.timers = {};
		
		dojo.subscribe("xray/data/item/time", this, function(data){
			this.time(data.log.id, data);
		});

		dojo.subscribe("xray/data/item/timeEnd", this, function(data){
			this.timeEnd(data.log.id, data);
		});			
	},
	
	time: function(name, data){
		if (this.timers[name] || !data.timestamp){
			return;
		}
		
		this.timers[name] = {
			start: data,
			end: null
		};
	},
	
	timeEnd: function(name, data){
		if (!this.timers[name] || !data.timestamp){
			return;
		}
		
		this.timers[name].end = data;
		
		this.renderTimer(this.timers[name]);
		delete this.timers[name];
	},
	
	renderTimer: function(timer){
		var duration = timer.end.timestamp - timer.start.timestamp;
		console.log(duration);
		if (timer.end.memory && timer.start.memory){
			var memory = timer.end.memory - timer.start.memory;   
		}
		
		var node = dojo.doc.createElement("div");
		node.innerHTML = duration; // + " " + memory ? ", "+memory : "";
		
		this.log.appendChild(node);
	}
});